package com.shiguiwu.springboot3.service;

import com.shiguiwu.springboot3.dto.request.ChatMessageReq;
import com.shiguiwu.springboot3.entity.ChatMessage;
import com.shiguiwu.springboot3.mapper.ChatMessageMapper;
import com.shiguiwu.springboot3.util.MemberContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @description: 聊天历史service
 * @author: stone
 * @date: Created by 2025/11/1 19:15
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springboot3.service
 */
@Service
public class ChatMessageService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    /**
     * 查询未读消息
     * @param sessionId
     * @return
     */
    public int queryUnreadCount(Long sessionId) {
        Example example = new Example(ChatMessage.class);

        example.createCriteria()
                .andEqualTo("session_id", sessionId)
                .andEqualTo("to_user_id", MemberContextUtils.getCurrentUserId());

        return chatMessageMapper.selectCountByExample(example);

    }

    public Integer read(Long sessionId) {
        Example example = new Example(ChatMessage.class);
        example.createCriteria()
                .andEqualTo("session_id", sessionId)
                .andEqualTo("is_read",0)
                .andEqualTo("to_user_id", MemberContextUtils.getCurrentUserId());

        List<ChatMessage> chatMessages = chatMessageMapper.selectByExample(example);
        if (chatMessages.isEmpty()) {
            return 0;
        }

        chatMessages.forEach(chatMessage -> {
            ChatMessage newChatMessage = new ChatMessage();
            newChatMessage.setIsRead((byte) 1);
            newChatMessage.setUpdatedAt(LocalDateTime.now());
            newChatMessage.setId(chatMessage.getId());
            chatMessageMapper.updateByPrimaryKey(newChatMessage);
        });


        return chatMessages.size();
    }

    public void save(ChatMessageReq req) {
        ChatMessage newChatMessage = new ChatMessage();
        newChatMessage.setContent(req.getMessage());
        newChatMessage.setIsRead((byte) 0);
        newChatMessage.setCreatedAt(LocalDateTime.now());
        newChatMessage.setFromUserId(req.getSenderId());
        newChatMessage.setToUserId(req.getReceiverId());
        newChatMessage.setSessionId(req.getSessionId());
        chatMessageMapper.insert(newChatMessage);
    }
}
